package com.cychat.mall.service.impl;

import com.Cychat.commons.entity.pojo.Favorite;
import com.Cychat.commons.entity.pojo.ShoppingCart;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cychat.mall.mapper.FavoriteMapper;
import com.cychat.mall.mapper.ShoppingCartMapper;
import com.cychat.mall.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Auther: 刘俊  <br/>
 * Date: 2025-10-31:下午 3:49  <br/>
 * Description: 收藏服务实现类
 */

@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {
    @Autowired
    FavoriteMapper favoriteMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Override
    public void addFavorite(Long userId, Integer productId) {
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setTargetId(productId);
        favorite.setType("product");
        favorite.setCreateTime(new Date());
        favoriteMapper.insert(favorite);
    }

    @Override
    public boolean isFavorite(Long userId, Integer productId) {
        Favorite favorite = favoriteMapper.selectOne(new LambdaQueryWrapper<Favorite>()
                .eq(Favorite::getUserId, userId)
                .eq(Favorite::getTargetId, productId)
                .eq(Favorite::getType, "product"));
        // 如果查询到收藏记录，返回true，否则返回false
        return favorite != null;
    }

    @Override
    public void deleteFavorite(Long userId, Integer productId) {
        favoriteMapper.delete(new LambdaQueryWrapper<Favorite>()
                .eq(Favorite::getUserId, userId)
                .eq(Favorite::getTargetId, productId));
    }

    @Override
    public List<Favorite> getFavoriteList(Long userId) {
        return favoriteMapper.selectList(new LambdaQueryWrapper<Favorite>()
                .eq(Favorite::getUserId, userId)
                .eq(Favorite::getType, "product"));
    }

    @Override
    public void addToCart(Long userId, Integer productId) {
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        shoppingCart.setProductId(productId);
        shoppingCart.setQuantity(1);
        shoppingCart.setSelected(1);
        shoppingCart.setCreateTime(new Date());
        shoppingCart.setUpdateTime(new Date());
        shoppingCartMapper.insert(shoppingCart);
    }
}
